﻿#include "datastorage.h"

CDataStorage *cmdStorage = 0;
CDataStorage::CDataStorage(QObject *parent) : QObject(parent)
{

}

//添加数据函数
void CDataStorage::AddToListData(const QByteArray &inArr)
{
    QByteArray byteArr(inArr);
    listData.push_back(byteArr);
    //根据byteArr数据添加附加信息
    countCmd = listData.count();
    QString str = QString::number(countCmd,10);
    listTag.push_back(str);

    //测试
    if(countCmd>100000)
    {
        SaveData();
    }
}

//返回指定位置开始长为len的数据包
QByteArrayList *CDataStorage::GetListData(qint32 index, qint32 len)
{
    if(listData.isEmpty() || countCmd<len) return 0;
    listOut = new QByteArrayList();
    for(qint32 i=index;i<index+len;i++)
    {
        listOut->push_back(listData.at(i));
    }
//    QByteArrayList *listOut = new QByteArrayList();listData.
//    qCopy(listData.begin()+index,listData.begin()+index+len,listOut);
    return listOut;
}

//设置存储文件名
bool CDataStorage::SetSaveFile(QString filename)
{
    //实例 QFile
    QFile file(filename);
    //判断文件是否存在
    if(file.exists())
    {
        saveFileName = filename+"(1)";
        return true;
    }
    else
    {
        //存在打开，不存在创建
        file.open(QIODevice::ReadWrite | QIODevice::Text);
        //关闭文件
        file.close();
        saveFileName = filename;
        return true;
    }

    return false;
}

//存储文件
bool CDataStorage::SaveData()
{
    QFile file(saveFileName);
    if(file.open(QIODevice::WriteOnly|QIODevice::Append))
    {
        QDataStream out(&file);
        out<<listData;
        file.close();
        listData.clear();
        countCmd=0;
        listTag.clear();
        return true;
}
    return false;
}
